<?php
class Ratings_model extends CI_Model {

    var $user_id = '';
    var $media_id = '';
    var $rating = '';
    
    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    
    function has_voted($media_id)
    {
        $user_id = $this->session->userdata('user_id');
        $this->db->select('*');
        $this->db->where('user_id', $user_id);
        $this->db->where('media_id', $media_id);
        $this->db->from('ratings');
           
        //$query = $this->db->get();
        $value = $this->db->count_all_results();
        return $value != '0';
    }
    
    function get_rating($media_id)
    {        
        $this->db->where('rating', '1');
        $this->db->where('media_id', $media_id);
        $this->db->from('ratings');   
        //$query = $this->db->get();
        $likes = $this->db->count_all_results(); //$query->first_row('array');
        
        
        $this->db->where('rating', '-1');
        $this->db->where('media_id', $media_id);
        $this->db->from('ratings'); 
        $dislikes = $this->db->count_all_results();
        
        $has_voted = $this->has_voted($media_id);
        
        $arr = array(
            "has_voted" => $has_voted,
            "likes" => $likes,
            "dislikes" => $dislikes,
            "vote_count" => $dislikes + $likes
        );
        return $arr;
    }
    
    function save_rating($video_id,$rating)
    {        
        $data = array(
               'user_id' => $this->session->userdata('user_id') ,
               'media_id' => $video_id,
               'rating' => $rating
            );
        
        $this->db->insert('ratings', $data);    
    }
}
?>